﻿using Future.Common.Const;
using Future.Common.Exception;
using Future.Web.Extensions;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Text.RegularExpressions;

namespace Future.Web.Filter
{
    /// <summary>
    /// 鉴权标记
    /// </summary>
    [AttributeUsage(AttributeTargets.Method)]
    public class PermissionAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// 权限标识
        /// </summary>
        public string Permission { get; set; }

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="permission"></param>
        public PermissionAttribute(string permission)
        {
            Permission = permission;
        }

        /// <summary>
        /// 动作鉴权
        /// </summary>
        /// <param name="context"></param>
        /// <exception cref="BusinessException"></exception>
        /// <exception cref="Exception"></exception>
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (string.IsNullOrEmpty(Permission))
            {
                throw new BusinessException("权限不能为空！");
            }

            bool result = false;
            List<string> permissionCodes = context.HttpContext.GetUserIdInfo().PermissionCodes;
            //进行正则表达式的匹配，以code开头
            Regex regex = new($"^{Permission.ToLower()}");
            foreach (string permissionCode in permissionCodes)
            {
                //如果存在超级管理员权限，直接放行
                if (SystemConst.ADMINPERMISSIONCODE.Equals(permissionCode))
                {
                    result = true;
                    break;
                }

                if (regex.IsMatch(permissionCode))
                {
                    result = true;
                    break;
                }
            }
            //用户的增删改查直接可以user:*即可

            if (!result)
            {
                throw new BusinessException("拦截未授权请求！");
            }
        }
    }
}
